package com.itheima.arithmetic.linked;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 单链表反转 1->2->3->4->5  ===> 5->4->3->2->1
 */
public class ReverseList {

    static class ListNode {
        int value;
        ListNode next;

        public ListNode(int value, ListNode next){
            this.value = value;
            this.next = next;
        }
    }

    /**
     * 链表是否出现环形
     */
    public static boolean hasCycle(ListNode head){
        Map<Integer, Integer> map = new HashMap<>();
        ListNode curr = head;
        while (curr.next != null) {
            int value = curr.value;
            if (map.containsKey(value)) {
                return true;
            } else {
                map.put(value, 1);
            }
            curr = curr.next;
        }
        return false;
    }

    public static boolean hasCycle1(ListNode head){
        Set<ListNode> set = new HashSet<>();
        ListNode curr = head;
        while (curr.next != null) {
            if (!set.add(curr)) {
                return true;
            }
            curr = curr.next;
        }
        return false;
    }

    /**
     * 双指针判断链表是否出现环形
     */
    public static boolean twoPoint(ListNode head) {
        ListNode low = head;
        ListNode quick = head.next;
        while (low != quick) {
            if (quick == null || quick.next == null ) {
                return false;
            }
            low = low.next;
            quick = quick.next.next;
        }
        return true;
    }


    // 方法一: 迭代
    public static ListNode iterate(ListNode head){
        if (head == null) {
            return null;
        }
        ListNode prev = null, next;
        ListNode current = head;
        while (current != null) {
            next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }
        return prev;
    }

    // 方法二: 递归
    public static ListNode recursion(ListNode head) {

        if (head == null || head.next == null) {
            return head;
        }

        ListNode new_head = recursion(head.next);
        head.next.next = head;
        head.next = null;
        return new_head;
    }

    public static void main(String[] args) {
        ListNode node5 = new ListNode(5, null);
        ListNode node4 = new ListNode(4, node5);
        ListNode node3 = new ListNode(3, node4);
        ListNode node2 = new ListNode(2, node3);
        ListNode node1 = new ListNode(1, node2);

        node5.next = node1;
//        ListNode prev = iterate(node1);
        boolean result = hasCycle(node1);
        boolean result1 = hasCycle1(node1);
        boolean result3 = twoPoint(node1);
    }
}
